package dc.sockettest;

import java.io.*;
import java.net.*;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

public class EchoServer {
	 public static void main(String[] args) throws Exception {
		 ThreadPoolExecutor executor = null;
		 ServerSocket listenSocket= null;
		 Socket socket=null;
		 try {
			 //线程池
			 executor = new ThreadPoolExecutor(5, 10, 200, TimeUnit.MILLISECONDS, new ArrayBlockingQueue<Runnable>(5));
			 //监听socket套接字
			 listenSocket=new ServerSocket(8189);

			 int count=0;
			 System.out.println("Server listening at 8189");

			 //监听socket→通信socket
			 while(true){
				 socket=listenSocket.accept();
				 count++;
				 System.out.println("The total number of clients is " + count + ".");
				 ServerThreads serverThread=new ServerThreads(socket,executor);
				 executor.execute(serverThread);
				 System.out.println("The number of threads in the ThreadPool:"+executor.getPoolSize());
				 System.out.println("The number of tasks in the Queue:" + executor.getQueue().size());
				 System.out.println("The number of tasks completed:"+executor.getCompletedTaskCount()+"\n");
			 }
		 }catch (Exception e){
			 System.out.println("Error:\n"+e);
		 }finally {
			 try {
				 if (socket!=null)
					 socket.close();
				 if (listenSocket!=null)
					 listenSocket.close();
				 if (executor!=null)
					 executor.shutdown();
			 }catch (Exception e){
				 System.out.println("Error:\n"+e);
			 }
		 }

	 }
}

class ServerThreads extends Thread {
	Socket socket = null;
	ThreadPoolExecutor executor = null;
	public ServerThreads(Socket socket,ThreadPoolExecutor executor) {
		this.socket = socket;
		this.executor=executor;
	}

	public void run(){
		//建立连接
		InputStream is=null;
		InputStreamReader isr=null;
		BufferedReader br=null;
		OutputStream os=null;
		PrintWriter pw=null;
		try {
			is = socket.getInputStream();
			isr = new InputStreamReader(is);
			br = new BufferedReader(isr);
			os = socket.getOutputStream();
			pw = new PrintWriter(os);
			String info=null;
			//通信
			while((info=br.readLine())!=null){
				System.out.println("Message from client to 通信socket"+this.getName()+" is: "+info+"\n");
				pw.println(info);
				pw.flush();
			}
		} catch (IOException e) {
			e.printStackTrace();
		}finally{
			try {
				if(pw!=null)
					pw.close();
				if(os!=null)
					os.close();
				if(br!=null)
					br.close();
				if(isr!=null)
					isr.close();
				if(is!=null)
					is.close();
				if(socket!=null)
					socket.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}
}